const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const views = require('koa-views');
const route = require('koa-route');
const axios = require('axios');
const cors = require('koa2-cors');

app.use(
  cors({
    origin: 'http://localhost:8080',
  })
);

const article = require('./routes/article');
const comment = require('./routes/comment');

app.use(bodyParser());

app.use(require('koa-static')(__dirname + '/public'));

app.use(
  views(__dirname + '/views', {
    extension: 'html',
  })
);

app.use(async (ctx, next) => {
  const start = new Date().getTime();
  await next();
  const ms = new Date().getTime() - start;
  console.log(`Time: ${ms}ms`);
});

const oauth = async (ctx) => {
  const requestToken = ctx.request.query.code;

  const clientID = '941f7f3ea2755d038b0f';
  const clientSecret = 'b8fd5be1e8187134a1b7a298e4fa148dee2a3601';

  const tokenResponse = await axios({
    method: 'post',
    url:
      'https://github.com/login/oauth/access_token?' +
      `client_id=${clientID}&` +
      `client_secret=${clientSecret}&` +
      `code=${requestToken}`,
    headers: {
      accept: 'application/json',
    },
  });

  const accessToken = tokenResponse.data.access_token;
  // console.log(`access token: ${accessToken}`);

  const result = await axios({
    method: 'get',
    url: `https://api.github.com/user`,
    headers: {
      accept: 'application/json',
      Authorization: `token ${accessToken}`,
    },
  });
  let { id, login, avatar_url } = result.data;
  console.log(id, login, avatar_url);
  ctx.body = '1';
  ctx.response.redirect(
    `http://localhost:8080/oauth/redirect?id=${id}&login=${login}&avatar_url=${avatar_url}`
  );
};

app.use(route.get('/oauth/redirect', oauth));

// routes
app.use(article.routes(), article.allowedMethods());
app.use(comment.routes(), comment.allowedMethods());

app.listen(3000);
